package com.tony.mulitithread.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Json转换工具类
 *
 */
public class JsonUtils {

    public static List<Field> fields = null;

    /**
     * 泛型List转List对象
     * 比JSON.parseArray(JSON.toJSONString(),T.class)
     * 快40倍
     *
     * @param obj 转换参数
     * @param cla 实体类
     * @param <T> 泛型
     * @return
     */
    public static <T> List<T> toList(Object obj, Class<T> cla) {
        List<T> list = new ArrayList<T>();
        //判断参数是否为List类型
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                //将父类对象强制转换为子类对象
                list.add(cla.cast(o));
            }
            return list;
        }
        return null;
    }

    /**
     * List对象转List<map>
     *
     * @param list
     * @return
     * @throws IllegalAccessException
     */
    public static List<Map<String, Object>> toMap(List<?> list) throws IllegalAccessException {
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Object o : list) {
            Map<String, Object> map = objToMap(o);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 对象转map
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objToMap(Object object) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(object));
        }
        return map;
    }

    /**
     * 反射方式拿到类的field集合
     */
    public static <T> void init(T vo) {
        Class<?> aClass = vo.getClass();
        fields = Lists.newArrayList();
        for (Class<?> i = aClass; i != Object.class; i = i.getSuperclass()) {
            Field[] declaredFields = i.getDeclaredFields();
            Collections.addAll(fields, declaredFields);
        }
    }

    /**
     * 反射方式  泛型List转为List对象
     *
     * @param vo
     * @param T
     * @param <T>
     * @return
     * @throws IllegalAccessException
     */
    public static <T> List<T> testReflection(List<?> vo, Class<T> T) throws IllegalAccessException {
        if (fields == null) {
            init(vo);
        }
        JSONObject jsonObject = new JSONObject();
        for (Field field : fields) {
            field.setAccessible(true);
            jsonObject.put(field.getName(), field.get(vo));
        }
        //未做类型校验 这样转换并不安全
        List<T> mapList = (List<T>)jsonObject.get("list");
        return mapList;
    }
}
